package com.elecbook.base.util;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import java.io.Serializable;


@Slf4j
public class SecurityUtil {

    public static String rolePrefix = "ROLE_";

    /**
     * 验证是否含有某个权限
     *
     * @param authority
     * @return
     */
    public static boolean hasAuthority(String authority) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        for (GrantedAuthority authorityTemp : authentication.getAuthorities()) {
            String role = authorityTemp.getAuthority();
            if (role.equals(authority) || role.equals(rolePrefix + authority)) {
                return true;
            }
        }
        return false;
    }

    /**
     * description 获取用户id
     *
     * @author zken
     * @CreateDate 2024/11/5 15:38:18
     */
    public static Integer getCurrentId() {
        // 获取security传输的信息
        // 规定，在security中封装的用户信息是只有一个用户id的
        try {
            Object principleObj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if (principleObj instanceof String) { // 如果是字符串
                Integer userId = Integer.parseInt((String) principleObj);
                return userId;
            }
        } catch (Exception e) {
            log.error("在获取user信息时刻发生了错误{}", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    /**
     * description 用户类型定义
     *
     * @author zken
     * @CreateDate 2024/11/5 15:38:07
     */
    @Getter
    @Setter
    @TableName("user")
    @ApiModel(value = "User对象", description = "")
    public class User implements Serializable {

        private static final long serialVersionUID = 1L;

        @ApiModelProperty("PK")
        @TableId(value = "id", type = IdType.AUTO)
        private Integer id;

        @ApiModelProperty("用户姓名")
        @TableField("name")
        private String name;

        @ApiModelProperty("用户头像")
        @TableField("avatar")
        private String avatar;

        @ApiModelProperty("账户或者电话")
        @TableField("phone")
        private String phone;

        @ApiModelProperty("密码")
        @TableField("password")
        private String password;

        @ApiModelProperty("openid，来自微信第三方id")
        @TableField("openid")
        private String openid;
    }
}
